﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Text.RegularExpressions;

using Ko2.Portal.SP_List;

namespace Ko2.Portal.Right
{

    public static class PermDocRight
    {

        #region Members
        static string siteUrl_wss = @"http://localhost/sites/shop/";
        static string siteUrl_App18 = @"http://localhost/shops/";
        static string listNamePermDocs = "Первичные документы";
        static string listRights = @"PermDocRight";

        #endregion

        public static Exception SetRoleItem(SPSite parSite, SPWeb parWeb, SPListItem parItem, String parShopName)
        {

            Exception ret = null;
            SPGroup mGroup = null;
            SPUser user = null;
            SPGroup group = null;
            SPFieldUserValueCollection ValueCollection = null;
            SPList listPermDoc = null;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(siteUrl_wss))
                {
                    using (SPWeb web = site.OpenWeb())
                    {

                        listPermDoc = web.Lists[listNamePermDocs];
                        SPListItem item = listPermDoc.GetItemById(parItem.ID);

                        if (!item.HasUniqueRoleAssignments)
                        {
                            item.BreakRoleInheritance(true);
                        }

                        //_____________
                        // shop group :
                        if (!String.IsNullOrEmpty(parShopName))
                        {
                            try
                            {
                                SPRoleAssignmentCollection ImageItemRoles = item.RoleAssignments;
                                while (ImageItemRoles.Count > 0)
                                    ImageItemRoles.Remove(0);
                                SPRoleDefinition roleDef = web.RoleDefinitions.GetByType(SPRoleType.Contributor);

                                if (!String.IsNullOrEmpty(parShopName))
                                {
                                    if (SPSecurityHelper.GetGroup(site, parShopName) != null)
                                    {
                                        mGroup = SPSecurityHelper.GetGroup(web, parShopName);
                                        SPRoleAssignment RoleAssignment = new SPRoleAssignment(mGroup);
                                        RoleAssignment.RoleDefinitionBindings.Add(roleDef);
                                        item.RoleAssignments.Add(RoleAssignment);
                                    }
                                }
                            }
                            catch (Exception err)
                            {
                                ret = new Exception(err.Message, err);
                            }
                        }

                        //_____________________
                        // PermDocRights list :
                        try
                        {
                            SPList list = web.Lists[listRights];
                            if (list != null)
                            {
                                foreach (SPListItem Item in list.Items)
                                {
                                    try
                                    {
                                        user = null;
                                        group = null;
                                        ValueCollection = null;
                                        Item.GetSPUser_or_SPGroup("Group", ref user, ref group, ref ValueCollection);

                                        SPRoleDefinition rolePerm = null;
                                        string type = Item["Perm"].ToString();
                                        if (type == "Administrator")
                                            rolePerm =
                                                web.RoleDefinitions.GetByType(SPRoleType.Administrator);
                                        if (type == "Contributor")
                                            rolePerm =
                                                web.RoleDefinitions.GetByType(SPRoleType.Contributor);
                                        if (type == "Reader")
                                            rolePerm =
                                                web.RoleDefinitions.GetByType(SPRoleType.Reader);
                                        if (rolePerm != null)
                                        {
                                            SPRoleAssignment RoleAssignment = null;
                                            if (group != null)
                                                RoleAssignment = new SPRoleAssignment(group);
                                            else if (user != null)
                                                RoleAssignment = new SPRoleAssignment(user);
                                            RoleAssignment.RoleDefinitionBindings.Add(rolePerm);
                                            item.RoleAssignments.Add(RoleAssignment);
                                        }
                                    }
                                    catch
                                    {
                                    }
                                } // foreach (SPListItem Item in list.Items)
                            } // if (list != null)
                        }
                        catch (Exception err)
                        {
                            ret = new Exception(err.Message, err);
                        }

                        //___________________
                        // owner user right :
                        try
                        {
                            string uidStr = parItem["uid"] == DBNull.Value ? "" : parItem["uid"].ToString();
                            if (!String.IsNullOrEmpty(uidStr))
                            {
                                uidStr = @"KORABLIK\" + uidStr;
                                user = null;
                                user = SPSecurityHelper.GetUserByName(web, uidStr, SPSecurityHelper.SPUserNameType.Login);
                                if(user != null)
                                {
                                    SPRoleDefinition roleDef = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
                                    SPSecurityHelper.SetUserPermission(parItem, user, roleDef.Name); // "Совместная работа"
                                }
                            }
                        }
                        catch (Exception err)
                        {
                            ret = new Exception(err.Message, err);
                        }

                    }
                }
            });
            return ret;
        }

        public static Exception SetRoleItem_App18(SPSite parSite, SPWeb parWeb, SPListItem parItem, String parShopName)
        {

            Exception ret = null;
            SPGroup mGroup = null;
            SPUser user = null;
            SPGroup group = null;
            SPFieldUserValueCollection ValueCollection = null;
            SPList listPermDoc = null;

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(siteUrl_App18))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {

                            listPermDoc = web.Lists[listNamePermDocs];
                            SPListItem item = listPermDoc.GetItemById(parItem.ID);

                            System.Threading.Thread.Sleep(0);
                            if (!item.HasUniqueRoleAssignments)
                            {
                                item.BreakRoleInheritance(true);
                            }
                            System.Threading.Thread.Sleep(0);

                            //_____________
                            // shop group :
                            if (!String.IsNullOrEmpty(parShopName))
                            {
                                try
                                {
                                    SPRoleAssignmentCollection ImageItemRoles = item.RoleAssignments;
                                    while (ImageItemRoles.Count > 0)
                                        ImageItemRoles.Remove(0);
                                    SPRoleDefinition roleDef = web.RoleDefinitions.GetByType(SPRoleType.Contributor);

                                    if (!String.IsNullOrEmpty(parShopName))
                                    {
                                        if (SPSecurityHelper.GetGroup(site, parShopName) != null)
                                        {
                                            mGroup = SPSecurityHelper.GetGroup(web, parShopName);
                                            SPRoleAssignment RoleAssignment = new SPRoleAssignment(mGroup);
                                            RoleAssignment.RoleDefinitionBindings.Add(roleDef);
                                            item.RoleAssignments.Add(RoleAssignment);
                                        }
                                    }
                                }
                                catch (Exception err)
                                {
                                    ret = new Exception(err.Message, err);
                                }
                            }

                            //_____________________
                            // PermDocRights list :
                            try
                            {
                                SPList list = web.Lists[listRights];
                                if (list != null)
                                {
                                    foreach (SPListItem Item in list.Items)
                                    {
                                        try
                                        {
                                            user = null;
                                            group = null;
                                            ValueCollection = null;
                                            Item.GetSPUser_or_SPGroup("Group", ref user, ref group, ref ValueCollection);

                                            SPRoleDefinition rolePerm = null;
                                            string type = Item["Perm"].ToString();
                                            if (type == "Administrator")
                                                rolePerm =
                                                    web.RoleDefinitions.GetByType(SPRoleType.Administrator);
                                            if (type == "Contributor")
                                                rolePerm =
                                                    web.RoleDefinitions.GetByType(SPRoleType.Contributor);
                                            if (type == "Reader")
                                                rolePerm =
                                                    web.RoleDefinitions.GetByType(SPRoleType.Reader);
                                            if (rolePerm != null)
                                            {
                                                SPRoleAssignment RoleAssignment = null;
                                                if (group != null)
                                                    RoleAssignment = new SPRoleAssignment(group);
                                                else if (user != null)
                                                    RoleAssignment = new SPRoleAssignment(user);
                                                RoleAssignment.RoleDefinitionBindings.Add(rolePerm);
                                                item.RoleAssignments.Add(RoleAssignment);
                                            }
                                        }
                                        catch
                                        {
                                        }
                                    } // foreach (SPListItem Item in list.Items)
                                } // if (list != null)
                            }
                            catch (Exception err)
                            {
                                ret = new Exception(err.Message, err);
                            }

                            //___________________
                            // owner user right :
                            try
                            {
                                string uidStr = parItem["uid"] == DBNull.Value ? "" : parItem["uid"].ToString();
                                if (!String.IsNullOrEmpty(uidStr))
                                {
                                    uidStr = @"KORABLIK\" + uidStr;
                                    user = null;
                                    user = SPSecurityHelper.GetUserByName(web, uidStr, SPSecurityHelper.SPUserNameType.Login);
                                    if (user != null)
                                    {
                                        SPRoleDefinition roleDef = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
                                        SPSecurityHelper.SetUserPermission(parItem, user, roleDef.Name); // "Совместная работа"
                                    }
                                }
                            }
                            catch (Exception err)
                            {
                                ret = new Exception(err.Message, err);
                            }

                        }
                    }
                });
            }
            catch (Exception err)
            {
                return new Exception(err.Message, err);
            }
            return ret;
        }

        public static void PermDocs_SetRoleItem(SPListItem item)
        {
            if (item["Магазин"] != null)
            {
                string[] shoparray = Regex.Split(item["Магазин"].ToString(), ";#");
                if (shoparray.Length > 1)
                    PermDocRight.SetRoleItem(item.Web.Site, item.Web, item, shoparray[1]);
            }
            else
                PermDocRight.SetRoleItem(item.Web.Site, item.Web, item, "");
        }

    }

}
